package com.cssw.fyzb.tps.client;

import com.cssw.fyzb.tps.model.vo.AuditResultVo;
import com.cssw.fyzb.tps.model.vo.ProcessMediaVo;
import com.cssw.fyzb.tps.model.vo.UploadSigVo;
import com.cssw.fyzb.tps.model.vo.UploadVodVo;
import com.cssw.fyzb.tps.util.VodSignature;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.vod.v20180717.models.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author Feng Chen
 */
@Component
public class VodClient {

    @Value("${vod.secretId}")
    private String secretId;

    @Value("${vod.secretKey}")
    private String secretKey;

    @Value("${vod.endpoint}")
    private String endpoint;

    @Value("${vod.sigValidDuration}")
    private Long signValidDuration;

    @Value("${vod.procedure}")
    private String procedure;

    private com.tencentcloudapi.vod.v20180717.VodClient delegate;

    private static final Logger logger = LoggerFactory.getLogger(VodClient.class);

    @PostConstruct
    public void start() {
        Credential credential = new Credential(secretId, secretKey);
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(endpoint);
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        delegate = new com.tencentcloudapi.vod.v20180717.VodClient(credential, "", clientProfile);
    }

    /**
     * 获取审核任务ID
     *
     * @param fileId
     * @return
     */
    public String getTaskId(String fileId) {
        DescribeTasksRequest request = new DescribeTasksRequest();
        request.setStatus("FINISH");
        request.setFileId(fileId);
        try {
            DescribeTasksResponse response = delegate.DescribeTasks(request);
            TaskSimpleInfo[] tasks = response.getTaskSet();
            if (tasks != null && tasks.length > 0) {
                return tasks[0].getTaskId();
            }
        } catch (TencentCloudSDKException e) {
            logger.error("", e);
        }
        return null;
    }

    /**
     * 获取任务审核状态
     *
     * @param videoId 视频编号
     * @return 0 - 未审核 1 - 审核完成
     */
    public AuditResultVo getAuditResult(String videoId) {

        AuditResultVo vo = new AuditResultVo();
        vo.setVideoId(videoId);

        // 获取审核任务编号
        String taskId = getTaskId(videoId);

        if (taskId != null) {
            // 查询任务明细
            DescribeTaskDetailRequest request = new DescribeTaskDetailRequest();
            request.setTaskId(taskId);
            try {
                DescribeTaskDetailResponse response = delegate.DescribeTaskDetail(request);
                ProcedureTask task = response.getProcedureTask();
                if (task != null) {
                    Float score = getScore(task.getAiContentReviewResultSet());
                    vo.setStatus("1");
                    vo.setScore(score);
                }
            } catch (TencentCloudSDKException e) {
                logger.error("", e);
            }
        }

        return vo;
    }

    public UploadVodVo uploadVod(String media, String cover) {
        VodUploadClient uploader = new VodUploadClient(secretId, secretKey);
        VodUploadRequest request = new VodUploadRequest();
        request.setMediaFilePath(media);
        request.setCoverFilePath(cover);
        request.setProcedure("测试任务流001");
        try {
            VodUploadResponse response = uploader.upload("ap-guangzhou", request);

            UploadVodVo vo = new UploadVodVo();
            vo.setFileId(response.getFileId());
            vo.setMediaUrl(response.getMediaUrl());
            vo.setCoverUrl(response.getCoverUrl());

            return vo;
        } catch (Exception e) {
            logger.error("", e);
        }
        return null;
    }

    public UploadSigVo uploadSig() {
        try {
            Long timestamp = System.currentTimeMillis() / 1000;
            UploadSigVo vo = new UploadSigVo();
            vo.setCurrentTimeStamp(timestamp);
            vo.setExpireTimeStamp(timestamp + signValidDuration);
            vo.setSignature(VodSignature.getSig(secretId, secretKey, timestamp, timestamp + signValidDuration));
            return vo;
        } catch (Exception e) {
            logger.error("", e);
        }
        return null;
    }

    public ProcessMediaVo processMedia(String fileId) {
        ProcessMediaByProcedureRequest req = new ProcessMediaByProcedureRequest();
        req.setFileId(fileId);
        req.setProcedureName(procedure);

        try {
            ProcessMediaByProcedureResponse resp = delegate.ProcessMediaByProcedure(req);
            ProcessMediaVo vo = new ProcessMediaVo();
            vo.setTaskId(resp.getTaskId());
            vo.setRequestId(resp.getRequestId());
            return vo;
        } catch (TencentCloudSDKException e) {
            logger.error("", e);
        }
        return null;
    }


    private Float getScore(AiContentReviewResult[] results) {
        Float score = 0f;
        for (AiContentReviewResult result : results) {

            // 视频鉴黄
            if (result.getPornTask() != null && result.getPornTask().getOutput() != null) {
                score = Math.max(score, result.getPornTask().getOutput().getConfidence());
            }

            // 音频文字鉴黄
            if (result.getPornAsrTask() != null && result.getPornAsrTask().getOutput() != null) {
                score = Math.max(score, result.getPornAsrTask().getOutput().getConfidence());
            }

            // 图像文字鉴黄
            if (result.getPornOcrTask() != null && result.getPornOcrTask().getOutput() != null) {
                score = Math.max(score, result.getPornOcrTask().getOutput().getConfidence());
            }

            // 视频鉴恐
            if (result.getTerrorismTask() != null && result.getTerrorismTask().getOutput() != null) {
                score = Math.max(score, result.getTerrorismTask().getOutput().getConfidence());
            }

            if (result.getTerrorismOcrTask() != null && result.getTerrorismOcrTask().getOutput() != null) {
                score = Math.max(score, result.getTerrorismOcrTask().getOutput().getConfidence());
            }

            // 视频鉴政
            if (result.getPoliticalTask() != null && result.getPoliticalTask().getOutput() != null) {
                score = Math.max(score, result.getPoliticalTask().getOutput().getConfidence());
            }

            if (result.getPornAsrTask() != null && result.getPornAsrTask().getOutput() != null) {
                score = Math.max(score, result.getPornAsrTask().getOutput().getConfidence());
            }

            if (result.getPornOcrTask() != null && result.getPornOcrTask().getOutput() != null) {
                score = Math.max(score, result.getPornOcrTask().getOutput().getConfidence());
            }

            if (result.getProhibitedAsrTask() != null && result.getProhibitedAsrTask().getOutput() != null) {
                score = Math.max(score, result.getProhibitedAsrTask().getOutput().getConfidence());
            }

            if (result.getProhibitedOcrTask() != null && result.getProhibitedOcrTask().getOutput() != null) {
                score = Math.max(score, result.getProhibitedOcrTask().getOutput().getConfidence());
            }

        }
        return 100 - score;
    }


}
